<template>
  <view class="popup-mask" v-if="visible" :catchtouchmove="true">
    <view class="popup-container" @click.stop>
      <view class="popup-content">
        <view class="search-box" v-if="searchIng">
          <view class="search-btn">正在搜索蓝牙</view>
          <view class="search-cancel" @click="stopSearch">取消</view>
        </view>
        <view class="search-box" v-else>
          <view class="search-btn">已停止搜索</view>
          <view class="search-cancel" @click="startSearch">搜索</view>
        </view>
        <scroll-view class="device-box" :scroll-y="true">
          <view class="device-item" v-for="item in devices" :key="item">
            <view class="label" @click="connectToDevice(item)">
              {{ item.localName ? item.localName : item.name }}
            </view>
            <view
              class="status status-ok"
              v-if="curDeviceId == item.deviceId"
              @click="disconnect(item.deviceId)">
              断开连接
            </view>
            <view class="status" v-else>未连接</view>
          </view>
        </scroll-view>
      </view>
      <view class="popup-actions">
        <button class="cancel-button" @click="handleCancel">取消</button>
        <button class="confirm-button" @click="handleConfirm">确认</button>
      </view>
    </view>
  </view>
</template>

<script>
import BluetoothManager from '@/utils/BluetoothManager'
const eventManager = require('@/utils/eventManager.js')
import { mapActions, mapGetters } from 'vuex'
export default {
  props: {
    curDeviceId: {
      type: String,
      default: '',
    },
  },
  name: 'DeviceMode',
  data() {
    return {
      searchIng: false,
      devices: [],
      visible: false,
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.startSearch()
      } else {
        this.devices = []
        this.stopSearch()
      }
    },
  },
  mounted() {},
  methods: {
    ...mapActions({
      setBatteryData: 'battery/setBatteryData',
    }),
    show() {
      this.visible = true
    },

    handleMaskClick() {
      this.$emit('close')
    },
    handleCancel() {
      this.visible = false
      this.$emit('cancel')
    },
    handleConfirm() {
      this.visible = false
      this.$emit('confirm')
    },
    sortDevices(devices) {
      // 获取上次连接的设备ID
      const lastConnectedDeviceId = uni.getStorageSync('lastConnectedDeviceId')
      // 过滤名称和重复的设备id
      let fileterDevice = devices.filter(
        (item) => item.name.includes('JJN')
        // (item.name && item.name != '未知设备' && !item.name.includes('HSJL')) ||
        // (item.localName && item.localName != '未知设备' && !item.localName.includes('HSJL'))
      )
      // 排序设备列表，将上次连接的设备放在最前面，并按名称排序
      return fileterDevice.sort((a, b) => {
        if (a.deviceId === lastConnectedDeviceId) return -1
        if (b.deviceId === lastConnectedDeviceId) return 1
        return (a.name || a.localName).localeCompare(b.name || b.localName)
      })
    },
    async startSearch() {
      try {
        console.log('开始搜索蓝牙...')
        await BluetoothManager.initBluetooth()
        BluetoothManager.searchDevices(this.onDeviceFound)
      } catch (err) {
        console.log(err)
      }
    },
    async onDeviceFound(devices) {
      try {
        this.searchIng = true
        const res = await BluetoothManager.getBluetoothDevices()
        this.devices = this.sortDevices(res.devices)
        // console.log('设备更新', this.devices)
      } catch (err) {
        console.error('获取设备列表失败', err)
      }
    },
    async stopSearch() {
      try {
        this.searchIng = false
        await BluetoothManager.stopSearchDevices()
      } catch (err) {
        console.log(err)
      }
    },

    //连接设备相关
    async connectToDevice(device) {
      console.log('连接中...', device)
      try {
        uni.showLoading({
          title: '连接中...',
        })
        await BluetoothManager.connectToDeviceForSanLi(device.deviceId)
        uni.setStorageSync('lastConnectedDeviceId', device.deviceId)
        this.setBatteryData({
          deviceId: device.deviceId,
          deviceName: device.localName,
          connected: true,
        })
        uni.hideToast()
        this.visible = false
      } catch (err) {
        uni.showToast({
          title: '连接失败',
          duration: 2000,
        })
      }
    },
    //断开连接
    async disconnect(deviceId) {
      await BluetoothManager.disconnect(deviceId)
    },
    showToast(params) {
      this.$refs.uToast.show({
        ...params,
        complete() {
          params.url &&
            uni.navigateTo({
              url: params.url,
            })
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 99999;
}

.popup-container {
  background-color: #fff;
  width: 80%;
  padding: 24rpx;
  border-radius: 10px;
  overflow: hidden;
}

.popup-content {
  padding: 20px;
}

.search-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  font-family: MicrosoftYaHei;
  font-size: 41rpx;
}
.search-box .search-btn {
  width: calc(100% - 178rpx);
  height: 78rpx;
  text-align: center;
  line-height: 77rpx;
  background: #574166;
  color: #ffffff;
  border-radius: 5rpx 5rpx 5rpx 5rpx;
}
.search-box .search-cancel {
  width: 158rpx;
  height: 76rpx;
  line-height: 78rpx;
  text-align: center;
  // background: #3a2b44;
  border-radius: 5rpx 5rpx 5rpx 5rpx;
  border: 1px solid #3a2b44;
  color: #3a2b44;
}
.popup-actions {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #574166;
}

.cancel-button,
.confirm-button {
  height: 85rpx;
  line-height: 85rpx;
  flex: 1;
  text-align: center;
  border: none;
  background: none;
  border-radius: 0;
  font-family: MicrosoftYaHei;
  font-size: 40rpx;
}

.cancel-button {
  color: #666666;
  border-right: 1px solid #574166;
}

.confirm-button {
  color: #ff0000;
}

.cancel-button:hover,
.confirm-button:hover {
  background-color: #f0f0f0;
}

.device-box {
  min-height: 300rxp;
  max-height: 800rpx;
  overflow-y: scroll;
}
.device-box .device-item {
  width: calc(100% - 40rpx);
  height: 100rpx;
  border-radius: 20rpx;
  margin-top: 20rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f9f9fb;
  color: #1e263b;
}

.device-box .device-item .label {
  width: 65%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 28rpx;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: 500;
}

.device-box .device-item .status {
  width: 140rpx;
  height: 58rpx;
  background-color: #e1e3ee;
  border-radius: 38rpx;
  font-size: 28rpx;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #1e263b;
  line-height: 58rpx;
  text-align: center;
}

.device-box .device-item .status-ok {
  background-color: #443f56;
  color: #ffffff;
}
</style>